﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Xml.Linq;
using FBEntities;
using XFControls;
using System.Net;
using System.Threading;
using System.Text.RegularExpressions;

namespace XDAFacebook
{
    public partial class SplashScreen : Form
    {
        private string curVer = "3.1 BETA";
        private string settingsFileName = "\\XDAFacebookSettings.xml";
        private string splashPictureLocation = "\\Resources\\splash.png";
        //private string versionURL = "http://forum.xda-developers.com/showpost.php?p=6404470";
        private string versionURL = "http://code.google.com/p/xda-winmo-facebook/wiki/CurrentVersion";
        private string _url;
        private string _updateDirectory = "\\updates";
        private string _filePath;
        private int percDone;

        public SplashScreen()
        {
            InitializeComponent();
            settingsFileName = LoginCustom.GetCurrent_Directory() + settingsFileName;

            this.BackColor = Color.FromArgb(59, 89, 150);

            SplashPicture.Image = new Bitmap(LoginCustom.GetCurrent_Directory() + splashPictureLocation);
            SplashPicture.SizeMode = PictureBoxSizeMode.StretchImage;
            _updateDirectory = LoginCustom.GetCurrent_Directory() + _updateDirectory;
        }

        private void SplashTimer_Tick(object sender, EventArgs e)
        {
            SplashTimer.Enabled = false;
            importCache();
            checkCurrentVersion();

            if (File.Exists(settingsFileName))
            {
                var settings = XDocument.Load(settingsFileName);

                if (settings.Root.Descendants("auth_key").Any())
                {
                    var auth = new Authentication(settings.Root.Element("auth_key").Value.Decrypt());

                    if (auth.TestForSuccess() == AuthenticationReturn.Success)
                    {
                        FBDataSource me = new FBDataSource(auth.AuthKey);
                        Main main = new Main();
                        XFItemControlUtils.Me = me;
                        main.Show();

                        this.Hide();
                        return;
                    }
                }
            }

            LoginCustom LoginCustom = new LoginCustom();
            LoginCustom.Show();
            this.Hide();
        }

        private void importCache()
        {
            WaitCallback cb = new WaitCallback((v) =>
            {
                Thread.CurrentThread.Priority = ThreadPriority.BelowNormal;
                XFGraphics.DoImport();
            });

            ThreadPool.QueueUserWorkItem(cb);
        }

        private void checkCurrentVersion()
        {
            //Regex reg = new Regex(@"<div class='post-message' id=""post_message_6404470""><p>current version (?<version>.*?)<br />.*?\s<a.*?href=""(?<link>.*?)""", RegexOptions.IgnoreCase | RegexOptions.Multiline);
            Regex reg = new Regex(@"<p>Current Version: (?<version>.*?)</p><p><a.*?href=['""](?<link>.*?)['""]", RegexOptions.IgnoreCase | RegexOptions.Multiline);
            var html = WebDownloader.DownloadHTML(versionURL);
            if (reg.IsMatch(html))
            {
                var match = reg.Match(html);
                if (!match.Groups["version"].Value.Trim().Equals(curVer))
                {
                    if (MessageBox.Show("Your app is out of date. Download latest version?", "Out Of Date", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button1) == DialogResult.Yes)
                    {
                        _url = match.Groups["link"].Value;
                        _filePath = _updateDirectory + "\\update " + match.Groups["version"].Value + ".cab";

                        WaitCallback cb = new WaitCallback(StartDownload);
                        ThreadPool.QueueUserWorkItem(cb);

                        lblPercDone.Height = Screen.PrimaryScreen.WorkingArea.Height / 4;

                        while (percDone != 100)
                        {
                            lblPercDone.Text = "Downloading file...\n" + percDone + "%";
                            Application.DoEvents();
                            Thread.Sleep(100);
                        }

                        lblPercDone.Text = "Downloading file...\n" + percDone + "%";
                        Application.DoEvents();
                        MessageBox.Show("Download Done");

                        if (MessageBox.Show("Would you like to install it now?", "Install", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button1) == DialogResult.Yes)
                        {
                            System.Diagnostics.Process.Start(_filePath, "");
                            Application.Exit();
                        }
                    }
                }
            }
        }

        private void StartDownload(object val)
        {
            try
            {
                if (!Directory.Exists(_updateDirectory))
                    Directory.CreateDirectory(_updateDirectory);

                HttpWebRequest webReq = (HttpWebRequest)HttpWebRequest.Create(_url);
                using (HttpWebResponse webRes = (HttpWebResponse)webReq.GetResponse())
                using (Stream fileBytes = webRes.GetResponseStream())
                using (FileStream saveStream = new FileStream(_filePath, FileMode.Create, FileAccess.Write))
                {
                    byte[] buffer = new byte[4096];
                    long bytesRead = 0;
                    long contentLength = webRes.ContentLength;

                    int read = 0;

                    do
                    {
                        read = fileBytes.Read(buffer, 0, buffer.Length);
                        saveStream.Write(buffer, 0, read);
                        bytesRead += read;

                        percDone = (int)(((double)bytesRead / (double)contentLength) * ((double)100));
                    } while (read > 0);
                }
            }
            catch
            {
            }
            percDone = 100;
        }
    }
}